package com.rockcent.message;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.RequestUtils;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.PlatformMark;
import com.rockcent.mall.lib.repository.MallRepository;
import com.rockcent.mall.lib.repository.UserAdminRepository;
import com.rockcent.mall.lib.repository.UserMallRepository;
import com.rockcent.mall.lib.repository.UserMerchantRepository;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by hone on 17-3-13.
 */
public class AuthUserInterceptor extends HandlerInterceptorAdapter {

    private final Logger log = LoggerFactory.getLogger(AuthUserInterceptor.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private String userToken;


    public AuthUserInterceptor(String userToken) {
        this.userToken = userToken;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI();
        log.info("======================>authUserInterceptor url:{}", url);
        String userToken = request.getHeader(this.userToken);
        if (StringUtils.isBlank(userToken)) {
            userToken = RequestUtils.getStringParameter(request, this.userToken);
        }
        log.info("======================>userToken : {}", userToken);
        if (StringUtils.isBlank(userToken)) {
            response.getWriter().print(JSON.toJSONString(new JsonResult<>("10001", "user_token 不能为空")));
            response.getWriter().close();
            return false;
        }
        String userInfoId = stringRedisTemplate.boundValueOps(UserInfo.REDIS_USER_TOKEN_PREFIX + userToken).get();
        if (StringUtils.isBlank(userInfoId)) {
            response.getWriter().print(JSON.toJSONString(new JsonResult<>("10003", "user_token 无效")));
            response.getWriter().close();
            return false;
        }
        String platformMark = request.getHeader("platformMark");
        if (StringUtils.isEmpty(platformMark)) {
            platformMark = RequestUtils.getStringParameter(request, "platformMark");
        }

        return super.preHandle(request, response, handler);
    }
}
